package com.jsz.peini.controller.app;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import java.util.Date;
import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.jsz.peini.bean.order.OrderInfo;
import com.jsz.peini.bean.seller.SellerInfo;
import com.jsz.peini.bean.task.PartyInfo;
import com.jsz.peini.bean.task.PartyUser;
import com.jsz.peini.bean.user.UserInfo;
import com.jsz.peini.common.bean.ResultMessage;
import com.jsz.peini.common.constants.Constants;
import com.jsz.peini.common.util.PeiniUtils;
import com.jsz.peini.common.util.ShieldTextFiltration;
import com.jsz.peini.common.util.ThreadUtil;
import com.jsz.peini.emchat.api.EasemobChatGroups;
import com.jsz.peini.service.seller.SellerInfoService;
import com.jsz.peini.service.task.PartyService;
import com.jsz.peini.service.user.UserInfoService;

@Controller
public class PartyController {
	@Autowired
	private PartyService partyService;
	@Autowired
	private UserInfoService userInfoService;
	@Autowired 
	SellerInfoService sellerInfoService;
	

	@ApiOperation("发布聚会")
	@RequestMapping(value = "/party", method=RequestMethod.POST, consumes="application/json")
	@ResponseBody
	public Object createPartyInfo(@RequestBody @Valid PartyInfo partyInfo, BindingResult binding) {
		String userId = ThreadUtil.getThreadInfo().getUserId();
		if(userId == null){
			return ResultMessage.FAIL.setMessage("用户不存在");
		}
		partyInfo.setUserId(userId);
		UserInfo userInfo = userInfoService.selectByPrimaryKey(userId);
		if(userInfo.getImgheadIsdelete() == null){
			userInfo.setImgheadIsdelete(0);
		}
		if (userInfo.getImgheadIsdelete()==1) {
			return ResultMessage.FAIL.setMessage("头像审核失败，非常抱歉，由于没有使用可看清脸的真实照片作为头像，您暂时无法进行任务操作，请尽快更换照片，得到更多人的喜欢吧~");
		}else if (userInfo.getImgheadIsdelete()==0) {
			return ResultMessage.FAIL.setMessage("头像正在审核中，您还无法体验任务互动功能~");
		}
		
		if(binding.hasErrors()){
			return ResultMessage.FAIL.setBindingResult(binding);
		}
		
		//敏感词检测
		String newDesc=ShieldTextFiltration.filter(partyInfo.getDescription());
		if (!newDesc.equals(partyInfo.getDescription())) {
			return ResultMessage.FAIL.setMessage("您发布的聚会描述涉及敏感字词请重新发送!");
		}
		String newPurpose=ShieldTextFiltration.filter(partyInfo.getPurpose());
		if (!newPurpose.equals(partyInfo.getPurpose())) {
			return ResultMessage.FAIL.setMessage("您发布的聚会目的涉及敏感字词请重新发送!");
		}
		//图片检测
		
		Date now = new Date();
		//不能选择当前时间之前的时间!
		if(partyInfo.getAppointedTime().before(now)){
			return ResultMessage.FAIL.setMessage("不能选择当前时间之前的时间!");
		}
		
		if(partyInfo.getAppointedTime().getTime() > (now.getTime() + Constants.MONTH_MIL_SECONDS)){
			return ResultMessage.FAIL.setMessage("只能发布30天之内的聚会!");
		}
		//任务选择时间点的上下1小时只能发布一条任务
		Integer cnt = partyService.selectCntByBetweenTime(partyInfo.getUserId(), partyInfo.getAppointedTime());
		if(cnt != null && cnt > 0){
			return ResultMessage.FAIL.setMessage("任务选择时间点的上下1小时只能发布一条任务");
		}
		
		//聚会人数检测
		if(partyInfo.getOfficial()){
			if(partyInfo.getMaxNum() > Constants.OFFICAL_PARTY_MAX_NUM){
				return ResultMessage.FAIL.setMessage("官方聚会不能超过" + Constants.OFFICAL_PARTY_MAX_NUM + "人");
			}
		}else{
			if(partyInfo.getMaxNum() > Constants.PERSONAL_PARTY_MAX_NUM){
				return ResultMessage.FAIL.setMessage("非官方聚会不能超过" + Constants.PERSONAL_PARTY_MAX_NUM + "人");
			}
		}
		
		if(partyInfo.getSellerType() == 1){
			if(partyInfo.getSellerInfoId() == null){
				return ResultMessage.FAIL.setMessage("店铺Id不能为空");
			}
			SellerInfo sellerInfo = sellerInfoService.selectById(partyInfo.getSellerInfoId());
			if(sellerInfo == null){
				return ResultMessage.FAIL.setMessage("店铺不存在");
			}
//			partyInfo.setSellerBigName(sellerInfo.get);
			partyInfo.setSellerBigType(sellerInfo.getSellerType());
			partyInfo.setSellerSmallType(Integer.parseInt(sellerInfo.getLabelsId()));
			partyInfo.setSellerSmallName(sellerInfo.getLabelsName());
		}
		
		//最多只能有三个任务同时在线
		partyService.createParty(partyInfo);
		//创建群
		ObjectNode dataObjectNode = JsonNodeFactory.instance.objectNode();
		dataObjectNode.put("groupname", partyInfo.getPurpose());
		dataObjectNode.put("desc", partyInfo.getDescription());
		dataObjectNode.put("approval", false);
		dataObjectNode.put("public", true);
		dataObjectNode.put("maxusers", partyInfo.getMaxNum());
		dataObjectNode.put("owner", userInfo.getUserPhone());
		ArrayNode arrayNode = JsonNodeFactory.instance.arrayNode();
		arrayNode.add(userInfo.getUserPhone());
		dataObjectNode.put("members", arrayNode);
		EasemobChatGroups.creatChatGroups(dataObjectNode);
		return ResultMessage.SUCCESS.setData(partyInfo);
	}
	
	
	private static String[] partyFields = new String[]{"id","prePay","pic","purpose","description","appointedTime","weekDayOfAppointedTime","partyStatus","maxNum","memberNum","payType","distance",
		"sellerInfo.sellerHead","sellerInfo.sellerName","sellerInfo.sellerAddress","userInfo.nickname","userInfo.age","userInfo.sex","members","userInfo.zmPoint","userInfo.credit"};
	@ApiOperation("获取聚会信息")
	@RequestMapping(value = "/party/{id}", method=RequestMethod.GET)
	@ResponseBody
	public Object getPartyInfo(@PathVariable("id") Integer id) {
		PartyInfo partyInfo = partyService.getPartyInfo(id);
		if(partyInfo == null){
			return ResultMessage.FAIL.setMessage("聚会不存在");
		}else{
			return ResultMessage.SUCCESS.setData(partyInfo,partyFields);
		}
	}
	
	@ApiOperation("获取聚会列表")
	@RequestMapping(value = "/party/list", method=RequestMethod.GET)
	@ResponseBody
	public Object getPartyList(
			@ApiParam(required=true, value="是否是官方聚会")  @RequestParam("offical") Boolean offical,
			@ApiParam(required=true)  @RequestParam("pageSize") Integer pageSize,
			@ApiParam(required=true)  @RequestParam("pageNum") Integer pageNum
			) {
		List<PartyInfo> partyInfoList = partyService.getPartyInfoList(offical,pageSize,pageNum);
		return ResultMessage.SUCCESS.setData(partyInfoList,partyFields);
	}
	

	@ApiOperation("参加聚会")
	@RequestMapping(value = "/joinParty/{partyId}", method=RequestMethod.POST, consumes="application/json")
	@ResponseBody
	public Object joinParty(@PathVariable("partyId") Integer partyId) {
		String userId = ThreadUtil.getThreadInfo().getUserId();
		if(userId == null){
			return ResultMessage.FAIL.setMessage("用户不存在");
		}
		PartyInfo partyInfo = partyService.getPartyInfo(partyId);
		if(partyInfo == null){
			return ResultMessage.FAIL.setMessage("聚会不存在");
		}
		UserInfo userInfo = userInfoService.selectByPrimaryKey(userId);
		if(partyInfo.getUserId().equals(userId)){
			return ResultMessage.FAIL.setMessage("不允许参加自己发起的聚会");
		}
		if(!PeiniUtils.isAddUserInfo(userInfo)){
			return ResultMessage.FAIL.setMessage("必要资料不全，请完善资料");
		}
		
		OrderInfo order = partyService.createPartyUser(partyInfo,userInfo);
		JSONObject resultData = new JSONObject();
		if(partyInfo.getPrePay() > 0){
			resultData.put("needPrePay", 1);
			resultData.put("payMoney", order.getPayMoney());
			resultData.put("partyInfoId", partyInfo.getId());
			resultData.put("orderId", order.getId());
		}else{
			resultData.put("needPrePay", 0);
		}
		return ResultMessage.SUCCESS.setData(resultData);
	}
	
	@ApiOperation("取消聚会")
	@RequestMapping(value = "/cancelParty/{partyId}", method=RequestMethod.POST, consumes="application/json")
	@ResponseBody
	public Object cancelParty(@PathVariable("partyId") Integer partyId) {
		String userId = ThreadUtil.getThreadInfo().getUserId();
		if(userId == null){
			return ResultMessage.FAIL.setMessage("用户不存在");
		}
		UserInfo userInfo = userInfoService.selectByPrimaryKey(userId);
		PartyUser pu = partyService.getPartyUser(partyId, userId);
		if(pu == null){
			return ResultMessage.FAIL.setMessage("聚会不存在");
		}
		if(pu.getStatus() != 1){
			return ResultMessage.FAIL.setMessage("聚会已取消");
		}
		
		if(pu.getPrePayed()){
			pu.setStatus(2);  //需要退费
		}else{
			pu.setStatus(3);
		}
		pu.setCancelType(1);
		partyService.cancelParty(pu);
		return ResultMessage.SUCCESS;
	}
	
	@ApiOperation("聚会买单")
	@RequestMapping(value = "/payParty/{partyId}", method=RequestMethod.POST, consumes="application/json")
	@ResponseBody
	public Object payParty(@PathVariable("partyId") Integer partyId) {
		String userId = ThreadUtil.getThreadInfo().getUserId();
		if(userId == null){
			return ResultMessage.FAIL.setMessage("用户不存在");
		}
		PartyInfo party = partyService.getPartyInfo(partyId);
		UserInfo userInfo = userInfoService.selectByPrimaryKey(userId);
		if(party == null){
			return ResultMessage.FAIL.setMessage("聚会不存在");
		}
		if(!userId.equals(party.getUserId())){
			return ResultMessage.FAIL.setMessage("只有聚会发起人才能买单");
		}
		if(party.getPartyStatus() == 1){
			return ResultMessage.FAIL.setMessage("聚会尚未开始");
		}else if(party.getPartyStatus() == 3 || party.getPartyStatus() == 4){
			return ResultMessage.FAIL.setMessage("您已经支付过费用,无需再次付费");
		}else if(party.getPartyStatus() == 5){
			return ResultMessage.FAIL.setMessage("聚会已取消");
		}
		
		OrderInfo order = partyService.payParty(party, userInfo);
		return ResultMessage.SUCCESS.setData(order);
	}
}
